# -*- coding: utf-8 -*-
from plugin_interface import PluginInterface
from flask import Blueprint, request, jsonify
import requests
import time
import json

class Plugin(PluginInterface):
    def get_plugin_info(self):
        return {
            "display_name": "Ping工具",
            "version": "1.1.0",
            "author": "插件开发者",
            "description": "向指定地址发送HTTP请求并显示响应结果"
        }
    
    def register_routes(self, blueprint):
        @blueprint.route('/cs', methods=['POST'])
        def ping_address():
            try:
                data = request.get_json()
                url = data.get('url', '').strip()
                
                if not url:
                    return jsonify({
                        'success': False,
                        'error': '请输入有效的URL地址'
                    })
                
                # 确保URL有协议前缀
                if not url.startswith(('http://', 'https://')):
                    url = 'http://' + url
                
                # 记录开始时间
                start_time = time.time()
                
                # 发送请求
                response = requests.get(
                    url, 
                    timeout=10,  # 10秒超时
                    allow_redirects=True,
                    headers={
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                    }
                )
                
                # 计算响应时间
                response_time = round((time.time() - start_time) * 1000, 2)
                
                # 构建响应结果
                result = {
                    'success': True,
                    'url': url,
                    'status_code': response.status_code,
                    'response_time': response_time,
                    'headers': dict(response.headers),
                    'content_preview': response.text[:500]  # 只显示前500个字符
                }
                
                return jsonify(result)
                
            except requests.exceptions.Timeout:
                return jsonify({
                    'success': False,
                    'error': '请求超时（10秒）'
                })
            except requests.exceptions.ConnectionError:
                return jsonify({
                    'success': False,
                    'error': '无法连接到目标地址'
                })
            except requests.exceptions.RequestException as e:
                return jsonify({
                    'success': False,
                    'error': f'请求错误: {str(e)}'
                })
            except Exception as e:
                return jsonify({
                    'success': False,
                    'error': f'发生未知错误: {str(e)}'
                })
    
    def get_menu_item(self):
        return {
            'title': 'Ping工具',
            'icon': 'fa fa-signal',
            'category': '网络工具'
        }
    
    def render_html(self):
        return """
        <div class="plugin-container">
            <div class="plugin-card">
                <div class="plugin-header">
                    <h3 class="plugin-title">Ping工具</h3>
                    <div class="plugin-tools">
                        <button type="button" class="plugin-collapse-btn">
                            <i class="fas fa-minus"></i>
                        </button>
                    </div>
                </div>
                <div class="plugin-body">
                    <div class="form-group">
                        <label for="pingUrl">要Ping的地址:</label>
                        <div class="input-group">
                            <input type="text" class="form-control" id="pingUrl" 
                                   placeholder="例如: example.com 或 http://example.com">
                            <div class="input-group-append">
                                <button class="btn btn-primary" id="pingButton">
                                    <i class="fas fa-play"></i> Ping
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div id="pingResult" class="result-container">
                        <div class="result-card">
                            <div class="result-header">
                                <h4 class="result-title">Ping结果</h4>
                            </div>
                            <div class="result-body">
                                <div id="resultContent"></div>
                            </div>
                        </div>
                    </div>
                    
                    <div id="pingError" class="error-alert"></div>
                </div>
                <div class="plugin-footer">
                    <small class="text-muted">
                        <i class="fas fa-info-circle"></i> 
                        此工具会向指定地址发送HTTP请求，并显示响应状态、时间和部分内容。
                    </small>
                </div>
            </div>
        </div>

        <style>
            .plugin-container {
                max-width: 800px;
                margin: 20px auto;
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            }
            
            .plugin-card {
                background: #fff;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
                overflow: hidden;
            }
            
            .plugin-header {
                background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
                color: white;
                padding: 15px 20px;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
            
            .plugin-title {
                margin: 0;
                font-size: 1.25rem;
                font-weight: 600;
            }
            
            .plugin-collapse-btn {
                background: transparent;
                border: none;
                color: white;
                cursor: pointer;
                font-size: 1rem;
            }
            
            .plugin-body {
                padding: 20px;
            }
            
            .form-group {
                margin-bottom: 20px;
            }
            
            label {
                display: block;
                margin-bottom: 8px;
                font-weight: 500;
                color: #333;
            }
            
            .input-group {
                display: flex;
            }
            
            .form-control {
                flex: 1;
                padding: 10px 15px;
                border: 1px solid #ddd;
                border-radius: 4px 0 0 4px;
                font-size: 14px;
                transition: border-color 0.3s;
            }
            
            .form-control:focus {
                border-color: #2575fc;
                outline: none;
                box-shadow: 0 0 0 2px rgba(37, 117, 252, 0.2);
            }
            
            .input-group-append {
                display: flex;
            }
            
            .btn {
                padding: 10px 20px;
                background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
                color: white;
                border: none;
                border-radius: 0 4px 4px 0;
                cursor: pointer;
                font-weight: 500;
                transition: all 0.3s;
            }
            
            .btn:hover {
                background: linear-gradient(135deg, #5a0db8 0%, #1c68f0 100%);
                transform: translateY(-2px);
                box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            }
            
            .btn:active {
                transform: translateY(0);
            }
            
            .result-container {
                display: none;
                margin-top: 25px;
            }
            
            .result-card {
                background: #f8f9fa;
                border-radius: 6px;
                overflow: hidden;
                box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
            }
            
            .result-header {
                background: #e9ecef;
                padding: 12px 15px;
                border-bottom: 1px solid #dee2e6;
            }
            
            .result-title {
                margin: 0;
                font-size: 1.1rem;
                color: #495057;
            }
            
            .result-body {
                padding: 15px;
            }
            
            .error-alert {
                display: none;
                margin-top: 20px;
                padding: 15px;
                background: #f8d7da;
                color: #721c24;
                border-radius: 4px;
                border: 1px solid #f5c6cb;
            }
            
            .ping-status {
                padding: 12px;
                border-radius: 4px;
                margin-bottom: 15px;
                font-weight: 500;
            }
            
            .ping-success {
                background: #d4edda;
                color: #155724;
                border: 1px solid #c3e6cb;
            }
            
            .ping-error {
                background: #f8d7da;
                color: #721c24;
                border: 1px solid #f5c6cb;
            }
            
            .header-table {
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 15px;
            }
            
            .header-table th, .header-table td {
                border: 1px solid #dee2e6;
                padding: 10px;
                text-align: left;
            }
            
            .header-table th {
                background-color: #f1f3f5;
                width: 30%;
                font-weight: 600;
            }
            
            .content-preview {
                background: #f1f3f5;
                border: 1px solid #dee2e6;
                border-radius: 4px;
                padding: 15px;
                max-height: 200px;
                overflow: auto;
                font-family: monospace;
                font-size: 13px;
                line-height: 1.5;
            }
            
            .plugin-footer {
                padding: 12px 20px;
                background: #f8f9fa;
                border-top: 1px solid #e9ecef;
                color: #6c757d;
                font-size: 0.85rem;
            }
            
            .text-muted {
                display: flex;
                align-items: center;
                gap: 8px;
            }
        </style>

        <script>
            document.addEventListener('DOMContentLoaded', function() {
                const pingButton = document.getElementById('pingButton');
                const pingUrl = document.getElementById('pingUrl');
                const pingResult = document.getElementById('pingResult');
                const resultContent = document.getElementById('resultContent');
                const pingError = document.getElementById('pingError');
                
                // 添加回车键支持
                pingUrl.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        pingButton.click();
                    }
                });
                
                pingButton.addEventListener('click', function() {
                    const url = pingUrl.value.trim();
                    
                    if (!url) {
                        showError('请输入要Ping的地址');
                        return;
                    }
                    
                    // 禁用按钮，防止重复点击
                    pingButton.disabled = true;
                    pingButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Pinging...';
                    
                    // 隐藏之前的结果
                    pingResult.style.display = 'none';
                    pingError.style.display = 'none';
                    
                    // 发送Ping请求
                    fetch('/plugin/ping/cs', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({url: url})
                    })
                    .then(response => {
                        // 首先检查响应状态
                        if (!response.ok) {
                            // 如果响应状态不是200-299，尝试读取错误信息
                            return response.text().then(text => {
                                throw new Error(`服务器错误: ${response.status} ${response.statusText}`);
                            });
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.success) {
                            displayResult(data);
                        } else {
                            showError(data.error || '未知错误');
                        }
                    })
                    .catch(error => {
                        showError(error.message);
                    })
                    .finally(() => {
                        // 重新启用按钮
                        pingButton.disabled = false;
                        pingButton.innerHTML = '<i class="fas fa-play"></i> Ping';
                    });
                });
                
                function displayResult(data) {
                    let html = `
                        <div class="ping-status ping-success">
                            <strong>Ping成功!</strong>
                        </div>
                        <table class="header-table">
                            <tr>
                                <th>目标地址</th>
                                <td>${escapeHtml(data.url)}</td>
                            </tr>
                            <tr>
                                <th>HTTP状态码</th>
                                <td>${data.status_code}</td>
                            </tr>
                            <tr>
                                <th>响应时间</th>
                                <td>${data.response_time} ms</td>
                            </tr>
                        </table>
                    `;
                    
                    // 添加响应头信息
                    if (data.headers) {
                        html += '<h5 class="mt-3">响应头信息:</h5>';
                        html += '<table class="header-table">';
                        for (const [key, value] of Object.entries(data.headers)) {
                            html += `<tr><th>${escapeHtml(key)}</th><td>${escapeHtml(value)}</td></tr>`;
                        }
                        html += '</table>';
                    }
                    
                    // 添加内容预览
                    if (data.content_preview) {
                        html += '<h5 class="mt-3">内容预览 (前500字符):</h5>';
                        html += `<div class="content-preview">${escapeHtml(data.content_preview)}</div>`;
                    }
                    
                    resultContent.innerHTML = html;
                    pingResult.style.display = 'block';
                }
                
                function showError(message) {
                    pingError.textContent = message;
                    pingError.style.display = 'block';
                }
                
                function escapeHtml(unsafe) {
                    return unsafe
                         .replace(/&/g, "&amp;")
                         .replace(/</g, "&lt;")
                         .replace(/>/g, "&gt;")
                         .replace(/"/g, "&quot;")
                         .replace(/'/g, "&#039;");
                }
            });
        </script>
        """